package com.hengtiansoft.productcrawl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProductParser {
	private String page;
	
	private SellerBean seller;
	
	private Pattern floatPattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
	
	private Pattern pattern = Pattern.compile(".*?<div class=\"result-price-seller\">.*?<span class=\"main-price\">(.*?)</span>.*?<p class=\"result-taxship\">(.*?)</p>.*?<div class=\"result-seller\">.*?<cite>(.*?)</cite>", Pattern.CASE_INSENSITIVE);

	
	public ProductParser(SellerBean seller) {
		this.seller = seller;
	}
	
	public ProductParser(String page, SellerBean seller) {
		this.page = page;
		this.seller = seller;
	}
	
	public void setPage(String page) {
		this.page = page;
	}
	
	public void setSeller(SellerBean seller) {
		this.seller = seller;
	}
	
	public PriceBean parse() throws Exception {
		double price;
		double totalPrice;
		String seller;

		try {
			Matcher matcher = pattern.matcher(page);
			while (matcher.find()) {
				seller = matcher.group(3).trim();
				if (this.seller.getName().equals(seller)) {
					price = parseDouble(matcher.group(1));
					totalPrice = parseDouble(matcher.group(2));
					if (totalPrice == 0.0) {
						totalPrice = price;
					}

					PriceBean priceBean = new PriceBean(null, this.seller,
							price, totalPrice - price, 0, totalPrice);
					return priceBean;
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return null;
	}
	
	private double parseDouble(String s) {
		Matcher floatMatcher = floatPattern.matcher(s);
		while (floatMatcher.find()) {
			return Double.parseDouble(floatMatcher.group());
		}
		return 0.0;
	}
}
